import {vtdata} from "../../../database/vtdata.js";


export var name = "vtlist"

export function render(){
    return `
        <style>
            .ul-continar {
                position: relative;
                text-align: center;
            }
            .page-item {
                user-select: none;
                cursor: pointer;
            }
            .vtlist-link {
                color : gray;
            }
            
            .vtlist-active {
                color : skyblue !important;
            }
            .li-goto {
                margin-left: 20px;
            }
            .li-goto input {
                width: 50px;height: 30px
            }
            .descrebtion {
                margin-right : 10px ;
                font-size: 16px;
                margin-left: 35%;
            }
            .descrebtion div{
                padding: 7px ;
            }
           
            .selector {
                margin-right : 20px ;
            }
        </style>
        <div class="container mt-5">
            <div></div>
            <div></div>
            
            <div class="table-responsive">
                <table class="table table-striped table-hover table-bordered">
                    <thead class="table-dark">
                        <tr>
                            <th scope="col">ID</th>
                            <th scope="col">姓名</th>
                            <th scope="col">部门</th>
                            <th scope="col">职位</th>
                            <th scope="col">邮箱</th>
                            <th scope="col">电话</th>
                            <th scope="col">入职日期</th>
                        </tr>
                    </thead>
                    <tbody>
                       
                    </tbody>
                </table>
            </div>
            
            <div class="">
                   <nav aria-label="Page navigation">
                   <ul class="pagination ul-continar">
                       
                   </ul>
                </nav>
            </div>
        </div>
    `
}


export function afterRender() {
    /*
    * 1.总数据量计算 userinfo.length
    * 2.添加分页显示 [5,10 *]
    * 3.计算总页码数  总数据量 / 分页显示量
    * */

    var total = vtdata.length;  //总数据量
    var pageShowNum = 10; //每一页显示多少
    var totalPageNum = Math.ceil(total / pageShowNum); //总页码数
    var btnNum = 5; //默认显示五个页码
    var pageNumSelect  = [5,10,15,20];  //每一页显示多少条
    var goto ; //
    //事件委派
    var vtlistActive;
    var thePageNum ;  //当前页码

    //当前的页码 1 需要显示 userinfo 索引 为 0~9 的数据
    //当前的页码 2 需要显示 userinfo 索引 为 10~19 的数据
    //当前的页码 3 需要显示 userinfo 索引 为 20~29 的数据
    //......
    //当前的页码 11 需要显示 userinfo 索引 为 100~109 的数据
    //结尾索引的公式 : pageShowNum * pageNow - 1 = 29
    //开始索引的公式 : pageShowNum * (pageNow -1)

    function computeIndex(pageNow){
        var startIndex = pageShowNum * (pageNow - 1);
        var endIndex = pageShowNum * pageNow - 1;

        return {//es6的简化对象
            startIndex,
            endIndex,
        }
    }

    var tbody = document.querySelector("tbody");

    //虚拟分页 : 减少重排
    function virtualUpdate(startIndex,endIndex){
        //获取tbody中所有的tr对象
        var trs = tbody.children; //[tr,tr]
        var newData = vtdata.slice(startIndex,endIndex+1); //[{}]
        for (let i = 0; i < newData.length; i++) {
            var tds = trs[i].children;

            var values = Object.values(newData[i]);

            for (let j = 0; j < values.length; j++) {
                tds[j].innerText = values[j];
            }
        }


        //10 - values.length(1) = 9
        //[1,10)
        for (var k = newData.length; k < trs.length; k++) {
            var tds = trs[k].children; //[]
            [...tds].forEach(function(td) {
                td.innerText = "";
            })
        }

    }

    //根据索引筛选数据
    function renderData(startIndex,endIndex){
        var html = "";
        for (let i = startIndex; i <= endIndex; i++) {
            if (vtdata[i]){
                html += createRow(vtdata[i]);
            }else{
                html += createRow();
            }
        }
        tbody.innerHTML = html;
    }
    /*
    * 1.分页的时候,需要删除以往的tbody中所有的对象
    * 2.从新创建很多个tr对象
    * -- 1和2实际上添加了很大的开销
    *
    * 解决方案 : 虚拟分页
    * 1.每页需要加载多少条数据 , 总页码也就知道了
    * 2.固定的创建 和 显示数据相关的 tr 对象
    * 3.换页的时候,将tr中的th或td的内容 直接执行替换  [问的是dom对象被删除和重新建立了吗?用的dom元素是不是始终是同一个]
    * */
    function createRow(data) {

        if(data){
            return `
                <tr>
                    <th scope="row">${data.id}</th>
                    <td>${data.name}</td>
                    <td>${data.department}</td>
                    <td>${data.position}</td>
                    <td>${data.email}</td>
                    <td>${data.phone}</td>
                    <td>${data.hireDate}</td>
                </tr>
            `;
        }else{
            return `
                <tr>
                    <th scope="row"></th>
                    <td></td>
                    <td></td>
                    <td></td>
                    <td></td>
                    <td></td>
                    <td></td>
                </tr>
            `;
        }

    }



    function createPageNumBtn(pagination){
        var html = `
                    <li class="descrebtion">
                        <div>
                            共${total}条数据; 共${totalPageNum}页;
                        </div>
                    </li>
                    
                    <li class="selector">
                        <button class="btn dropdown-toggle" type="button" id="autoDirectionDropdown" data-bs-toggle="dropdown">
                            ${pageShowNum}条/页
                        </button>
                        <ul class="dropdown-menu dropdown-defined-ul" >
                      
                        </ul>
                    </li>
                    
                    <li class="page-item" id="prevBtn">
                        <a class="page-link"  id="Previous" aria-label="Previous">
                            <span aria-hidden="true" id="prevSpan">&laquo;</span>
                        </a>
                    </li>`;


        for (let i = 1; i <= totalPageNum; i++) {
            html +=`<li class="page-item page-num" >
                        <a class="page-link vtlist-link" data-page="${i}">
                            ${i}
                        </a>
                     </li>`;
        }

        html += `
        <li class="page-item" id="nextBtn">
            <a class="page-link"  aria-label="Next" id="Next">
                <span aria-hidden="true" id="nextSpan">&raquo;</span>
            </a>
        </li>
        
        <li class="li-goto">
          <span>前往:</span>
          <input type="text" id="goto" >
          <span>/页</span>
        </li>
    `;

        //首次加载的时候,自动创建分页栏
        pagination.innerHTML = html;

        selectPageNum();

        //下拉列表绑定事件
        var dropdownMenuWithPageNum = document.querySelector(".dropdown-defined-ul");
        var autoDirectionDropdown = document.querySelector("#autoDirectionDropdown");
        dropdownMenuWithPageNum.onclick = function(e){
            if(e.target.tagName === "A"){
                var num = e.target.getAttribute("data-num");
                pageShowNum = num;
                autoDirectionDropdown.innerHTML = e.target.innerHTML;
                totalPageNum = Math.ceil(total / pageShowNum); //总页码数
                //当替换过一页显示多少条以后,需要对比 当前页码(11) 和 新的页码(7) 谁大
                //新的页码大 , 则不采取措施
                //当前页码大 , 则将sessionStorage中的页码替换为 新的页码的最后一页

                if(thePageNum > totalPageNum){
                    thePageNum = totalPageNum;
                    sessionStorage.setItem("pageNum", thePageNum);
                }


                createPageNumBtn(pagination);
                clickActive();
            }
        }

        goto = document.getElementById("goto");

        gotoEvent(goto);
    }
    //<li class="page-item"><a class="page-link" href="#">1</a></li>
    //循环页码 放入到ul中 : nextBtn之前 prevBtn之后
    var pagination = document.querySelector(".pagination");

    createPageNumBtn(pagination);



    function clickActive(e) {
        var virtualSign  = true; //什么时候使用虚拟分页的信号量
        e?.preventDefault();
        if(e?.target.parentElement.classList.contains("page-num")){ //e.target 代表数字页码
            thePageNum = parseInt(e.target.getAttribute("data-page"));
            sessionStorage.setItem("pageNum", thePageNum);
        }else if(!e){  //e===undefined  首次加载
            if(!thePageNum) {
                if(sessionStorage.getItem("pageNum") === null){//为空
                    thePageNum = 1;
                    sessionStorage.setItem("pageNum", thePageNum);
                }else{//不为空
                    thePageNum = parseInt(sessionStorage.getItem("pageNum"));
                }
            }
            virtualSign = false;
        }else if (e?.target.parentElement.id === "prevBtn"
            || e?.target.id === "Previous"
            || e?.target.id === "prevSpan"
        ){
            if(thePageNum > 1){
                updateActive(--thePageNum);
                sessionStorage.setItem("pageNum", thePageNum);
            }
        }else if(
            e?.target.parentElement.id === "nextBtn"
            || e?.target.id === "Next"
            || e?.target.id === "nextSpan"
        ){
            if(thePageNum < totalPageNum){
                updateActive(++thePageNum);
                sessionStorage.setItem("pageNum", thePageNum);
            }

        }else{
            return;
        }

        var indexObj = computeIndex(thePageNum);
        if(virtualSign){
            virtualUpdate(indexObj.startIndex,indexObj.endIndex);
        }else{
            renderData(indexObj.startIndex,indexObj.endIndex);
        }

        goto.value = thePageNum;
        updateActive(thePageNum);
        showPageBtn(thePageNum);

    }

    //生成一页显示多少条的li的
    function selectPageNum() {
        var dropdownMenuWithPageNum = document.querySelector(".dropdown-defined-ul");
        var html = "";
        pageNumSelect.forEach(function(item){
            html +=`<li><a class="dropdown-item" href="javascript:;" data-num="${item}" >${item}条/页</a></li>`
        })
        dropdownMenuWithPageNum.innerHTML = html;
    }

    //修改激活状态的函数
    function updateActive(thePageNum) {
        vtlistActive?.classList.remove("vtlist-active");
        vtlistActive = document.querySelector(`[data-page="${thePageNum}"]`);
        vtlistActive.classList.add("vtlist-active");
    }

    //显示页面按钮作为一个独立功能
    /*
    * 如果当前的page=1,则向后显示4个
    * 如果当前的page=2,则向前显示1个,向后显示3个
    *
    * 中间标签,则向前显示2个,向后显示2个
    * */

    function showPageBtn(page=1){

        var links = document.querySelectorAll(".vtlist-link");
        links.forEach(function(link){
            link.style.display = "inline-block";
        })
        if(page === 1 || page === 2 ){
            for(let i = btnNum; i < links.length; i++){
                links[i].style.display = "none";
            }

        }else if(page === links.length || page === links.length - 1){
            for(let i = links.length - btnNum -1; i > -1; i--){
                links[i].style.display = "none";
            }
        }else{
            for (let i = page -2 - 2; i > -1 ; i--) {
                links[i].style.display = "none";
            }
            for (let i = page + 2 ; i <  links.length; i++) {
                links[i].style.display = "none";
            }
        }
    }


   function gotoEvent(goto){
       goto.onfocus = function(e){

           var oldValue = e.target.value; //记录原来的页码

           window.onkeydown = function(event){
               if(event.key === "Enter"){
                   var intPage = parseInt(e.target.value);

                   if(Number.isNaN(intPage)){//是个NaN
                       e.target.value = oldValue;
                       return;
                   }

                   //传递进来的是个数字
                   if( !(intPage > 0 && intPage <= totalPageNum) ){
                       e.target.value = oldValue;
                       return;
                   }

                   //正常的
                   thePageNum = intPage;
                   sessionStorage.setItem("pageNum", thePageNum);
                   var indexObj = computeIndex(thePageNum);
                   virtualUpdate(indexObj.startIndex,indexObj.endIndex);
                   //修改字体的颜色
                   updateActive(thePageNum);
                   showPageBtn(thePageNum);

                   window.onkeydown = null;
               }
           }

           goto.onblur = function(e){
               window.onkeydown = goto.onblur = null;
           }
       }
   }



    pagination.addEventListener("click", clickActive);
    clickActive(); //默认加载

}

